package com.stooges.adjustment.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.stooges.adjustment.entity.ApplyLog;
import com.stooges.adjustment.entity.CollegeAccount;
import com.stooges.adjustment.entity.LocalOauth;
import com.stooges.adjustment.entity.Teacher;
import com.stooges.adjustment.form.AccountForm;
import com.stooges.adjustment.form.ApplyAlterForm;
import com.stooges.adjustment.form.ApplyConditionForm;
import com.stooges.adjustment.form.DirectCollectForm;
import com.stooges.adjustment.form.DirectionForm;
import com.stooges.adjustment.form.MajorCollectionForm;
import com.stooges.adjustment.form.MajorForm;
import com.stooges.adjustment.util.Constants;
import com.stooges.adjustment.util.Md5Util;
import com.stooges.adjustment.view.ApplierView;
import com.stooges.adjustment.view.ApplyView;
import com.stooges.adjustment.view.DirectCollectView;
import com.stooges.adjustment.view.DirectionView;
import com.stooges.adjustment.view.MajorCollectionView;

/**
 * 学院逻辑处理
 * @author 张超
 *
 */
@Service
public class CollegeService {
	@Resource
	private SqlSession sqlSession;
	/**
	 * 检查用户名重复性
	 * @param username 用户名
	 * @param error 错误
	 * @return 是否重复
	 */
	public boolean validateAccountDuplicate(String username,Map<String,String> errorMap){
		LocalOauth localOauth = sqlSession.selectOne("localOauthDao.findOauthByUsername",username);
		if(localOauth==null){
			return false;
		}else{
			errorMap.put("error","用户名重复");
			return true;
		}
	}
	/**
	 * 添加帐号
	 * @param accountForm 帐号表单
	 * @param operatorId 操作者ID
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean addAccount(AccountForm accountForm,Long operatorId)throws Exception{
		//查询所在学院
		CollegeAccount collegeAccount = sqlSession.selectOne("collegeAccountDao.findAccountByOauthId",operatorId);
		
		//组装数据
		LocalOauth localOauth = new LocalOauth();
		String username = accountForm.getUsername();
		if(Character.isDigit(username.charAt(0))){
			username = "T"+username;
		}
		localOauth.setUsername(username);
		localOauth.setPassword(Md5Util.MD5(accountForm.getPassword()));
		if(accountForm.getAccountType()==Constants.ACCOUNT_TYPE_OPEN){
			localOauth.setRoleId(Constants.ROLE_TEACHER1);
		}else{
			localOauth.setRoleId(Constants.ROLE_TEACHER2);
		}
		localOauth.setStatus(Constants.LOCAL_OAUTH_STATUS_ACTIVATED);
		localOauth.setCreateTime(System.currentTimeMillis()/1000);
		
		//添加帐号信息
		sqlSession.insert("localOauthDao.saveLocalOauth", localOauth);
		Teacher teacher = new Teacher();
		teacher.setLocalOauthId(localOauth.getId());
		teacher.setCollegeId(collegeAccount.getCollegeId());
		teacher.setName(accountForm.getName());
		return sqlSession.insert("teacherDao.saveTeacher",teacher)>0;
	}
	/**
	 * 更新学生申请状态
	 * @param applyAlterForm 要修改的申请信息表单
	 * @param operatorId 操作者ID
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean updateApplyStatus(ApplyAlterForm applyAlterForm)throws Exception{
		if(applyAlterForm==null){
			return false;
		}
		//生成操作日志
		ApplyLog applyLog = new ApplyLog();
		applyLog.setApplierId(applyAlterForm.getStudentId());
		applyLog.setOperateId(applyAlterForm.getOperatorId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        String dateNowStr = sdf.format(new Date());
		applyLog.setOperateDate(dateNowStr);
		String json = JSON.toJSONString(applyLog);
		applyAlterForm.setAllLog(json);
		applyAlterForm.setLastLog(json);
		applyAlterForm.setModifyTime(System.currentTimeMillis()/1000);
		
		boolean updateStudentResult = true;
		if (applyAlterForm.getStatus().equals(Constants.TARGET_STATUS_ENROLL)){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("localOauthId", applyAlterForm.getStudentId());
			map.put("admissionStatus", Constants.STUDENT_STATUS_ENROLL);
			updateStudentResult = sqlSession.update("studentDao.updateStudentStatus",map)>0;
		}
		if(updateStudentResult){
			return sqlSession.update("targetDao.updateApplyStatus",applyAlterForm)>0;
		}else{
			return false;
		}
	}
	
	/**
	 * 根据条件查询所有的申请记录
	 * @param applyConditionForm 申请条件
	 * @return
	 */
	public PageInfo<ApplyView> findAllApply(ApplyConditionForm applyConditionForm) {
		int pageNum = 1;
		int pageSize = 10;
		if(applyConditionForm!=null){
			if(applyConditionForm.getPageNum()!=null){
				pageNum = applyConditionForm.getPageNum();
			}
			if(applyConditionForm.getPageSize()!=null){
				pageSize = applyConditionForm.getPageSize();
			}
		}
		PageHelper.startPage(pageNum, pageSize);
		List<ApplyView> applyList = sqlSession.selectList("targetDao.findAllApply",applyConditionForm);
		return new PageInfo<ApplyView>(applyList);
	}
	/**
	 * 根据学生ID查询申请者全部信息
	 * @param studentId 学生ID
	 * @param operateId 操作者ID
	 * @param roleId 操作者权限ID
	 * @return 
	 */
	public ApplierView findApplierDetail(Long studentId, Long operateId,Integer roleId) {
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("studentId", studentId);
		map.put("operateId", operateId);
		map.put("roleId", roleId);
		return sqlSession.selectOne("targetDao.findApplierDetail",map);
	}
	/**
	 * 根据登录者ID查询所有专业方向集合
	 * @param id 登录者ID
	 * @return
	 */
	public MajorCollectionView findMajorCollectByOauthId(Long id) {
		return sqlSession.selectOne("collegeDao.findMajorCollectByOauthId",id);
	}
	
	/**
	 * 保存专业集合
	 * @param majorCollectionForm 专业集合信息
	 * @param id 登录者ID
	 * @return
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean fillMajorCollection(MajorCollectionForm majorCollectionForm,Long id)throws Exception {
		//查询该专业下所有的专业集合信息与数据库中进行比较
		MajorCollectionView majorCollectionView = findMajorCollectByOauthId(id);
		if(majorCollectionView==null ||
				majorCollectionView.getDirectCollectList()==null
				||majorCollectionView.getDirectCollectList().isEmpty()){
			//直接全部保存
			List<DirectCollectForm> directionCollection = majorCollectionForm.getDirectCollectList();
			if(directionCollection!=null && !directionCollection.isEmpty()){
				for (DirectCollectForm directCollectForm : directionCollection) {
					directCollectForm.setCollegeId(majorCollectionForm.getCollegeId());
					directCollectForm.setStatus(Constants.MAJOR_STATUS_ACTIVATED);
					directCollectForm.setCreateTime(System.currentTimeMillis()/1000);
					sqlSession.insert("majorDao.addMajor",directCollectForm);
					List<DirectionForm> directList = directCollectForm.getDirectList();
					if(directList!=null && !directList.isEmpty()){
						for (DirectionForm directionForm : directList) {
							directionForm.setMajorId(directCollectForm.getMajorId());
							directionForm.setStatus(Constants.DIRECT_STATUS_ACTIVATED);
							directionForm.setCreateTime(System.currentTimeMillis()/1000);
						}
						sqlSession.insert("directionDao.addDirects",directList);
					}
				}
			}
		}else{
			List<DirectCollectView> dbDirectCollect = majorCollectionView.getDirectCollectList();//数据库中的专业集合
			List<DirectCollectForm> inputDirectionCollect = majorCollectionForm.getDirectCollectList(); //提交的专业集合
			
			//更新或保存专业
			List<DirectCollectForm> updateMajor = new ArrayList<DirectCollectForm>();
			List<DirectCollectForm> addMajor = new ArrayList<DirectCollectForm>();
			for (DirectCollectView directCollectView : dbDirectCollect) {
				if(inputDirectionCollect==null || inputDirectionCollect.isEmpty()){
					break;
				}
				for (DirectCollectForm directCollectForm : inputDirectionCollect) {
					directCollectForm.setCollegeId(majorCollectionView.getCollegeId());
					if(directCollectView.getMajorId().equals(directCollectForm.getMajorId())){
						updateMajor.add(directCollectForm);
					}
				}
			}
			if(updateMajor!=null && !updateMajor.isEmpty()){
				sqlSession.update("majorDao.updateMajors",updateMajor);
			}
			
			addMajor.addAll(inputDirectionCollect);
			addMajor.removeAll(updateMajor);
			if(addMajor!=null&&!addMajor.isEmpty()){
				for(DirectCollectForm majorForm: addMajor){
					majorForm.setStatus(Constants.MAJOR_STATUS_ACTIVATED);
					majorForm.setCreateTime(System.currentTimeMillis()/1000);
					sqlSession.insert("majorDao.addMajor",majorForm);
				}
				for(DirectCollectForm inputMajorForm :inputDirectionCollect){
					for(DirectCollectForm majorForm: addMajor){
						if(inputMajorForm.getMajorName().equals(majorForm.getMajorName())){
							inputMajorForm.setMajorId(majorForm.getMajorId());
						}
					}
					List<DirectionForm> directList = inputMajorForm.getDirectList();
					if(directList!=null && !directList.isEmpty()){
						for (DirectionForm directionForm : directList) {
							directionForm.setMajorId(inputMajorForm.getMajorId());
						}
					}
				}
			}
			
			//更新或保存专业方向
			for (DirectCollectView directCollectView : dbDirectCollect) {
				if(inputDirectionCollect==null || inputDirectionCollect.isEmpty()){
					break;
				}
				if(directCollectView.getDirectList()==null||directCollectView.getDirectList().isEmpty()){
					List<DirectCollectForm> directionCollection = majorCollectionForm.getDirectCollectList();
					if(directionCollection!=null && !directionCollection.isEmpty()){
						for (DirectCollectForm directCollectForm : directionCollection) {
							List<DirectionForm> directList = directCollectForm.getDirectList();
							if(directList!=null && !directList.isEmpty() && directCollectView.getMajorId().equals(directCollectForm.getMajorId())){
								for (DirectionForm directionForm : directList) {
									directionForm.setMajorId(directCollectForm.getMajorId());
									directionForm.setStatus(Constants.DIRECT_STATUS_ACTIVATED);
									directionForm.setCreateTime(System.currentTimeMillis()/1000);
								}
								sqlSession.insert("directionDao.addDirects",directList);	
							}
						}
					}
				}else{
					List<DirectionView> dbDirects = directCollectView.getDirectList();
					List<DirectionForm> updateDirects = new ArrayList<DirectionForm>();
					List<DirectionForm> addDirects = new ArrayList<DirectionForm>();
					List<DirectionForm> allDirects = new ArrayList<DirectionForm>();
					
					for(DirectCollectForm inputDirectCollect : inputDirectionCollect){
						if(inputDirectCollect!=null
								&&inputDirectCollect.getDirectList()!=null
								&&!inputDirectCollect.getDirectList().isEmpty()){
							List<DirectionForm> inputDirections= inputDirectCollect.getDirectList();
							for (DirectionForm inputDirect : inputDirections) {
								allDirects.add(inputDirect);
								for (DirectionView dbDirect : dbDirects) {
									if(inputDirect!=null && inputDirect.getId()!=null&&
											dbDirect.getId().equals(inputDirect.getId())){
										updateDirects.add(inputDirect);
									}
								}
							}
						}
					}
					
					if(updateDirects!=null&&!updateDirects.isEmpty()){
						sqlSession.update("directionDao.updateDirects",updateDirects);
						addDirects.addAll(allDirects);
						addDirects.removeAll(updateDirects);
					}
					if(addDirects!=null&&!addDirects.isEmpty()){
						for (DirectionForm directionForm : addDirects) {
							directionForm.setStatus(Constants.DIRECT_STATUS_ACTIVATED);
							directionForm.setCreateTime(System.currentTimeMillis()/1000);
						}
						sqlSession.update("directionDao.addDirects",addDirects);
					}
				}
			}
		}
		
		return true;
	}
	/**
	 * 添加专业表单
	 * @param majorForm
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean addMajor(MajorForm majorForm)throws Exception {
		if(majorForm==null){
			return false;
		}
		majorForm.setCreateTime(System.currentTimeMillis()/1000);
		majorForm.setStatus(Constants.MAJOR_STATUS_ACTIVATED);
		return sqlSession.insert("majorDao.addMajor2",majorForm)>0;
	}
	/**
	 * 添加专业方向表单
	 * @param directionForm
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor=Exception.class)
	public boolean addDirect(DirectionForm directionForm)throws Exception {
		if(directionForm==null){
			return false;
		}
		directionForm.setCreateTime(System.currentTimeMillis()/1000);
		directionForm.setStatus(Constants.MAJOR_STATUS_ACTIVATED);
		return sqlSession.insert("directionDao.addDirection",directionForm)>0;
	}
	
	/**
	 * 根据条件查询所有导出excel用的申请记录
	 * @param applyConditionForm
	 * @return
	 */
	public List<ApplyView> findExcelApplys(ApplyConditionForm applyConditionForm) {
		if(applyConditionForm==null){
			applyConditionForm = new ApplyConditionForm();
		}
		List<ApplyView> applyList = sqlSession.selectList("targetDao.findExcelApplys",applyConditionForm);
		return applyList;
	}
}
